define(function(require) {

  var $ = require("jquery");
  var _ = require("underscore");
  var Backbone = require("backbone");
  var L = require("leaflet");
  var Utils = require("utils");
  var Parse = require("parse");
  var Autocomplete = require("autocomplete");
  var MapView = Utils.Page.extend({

    constructorName: "MapView",

    id: "map",

    events: {
      "touchend #invio_ricerca": "addMarkerToMap"
    },

    initialize: function(options) {
      // load the precompiled template
      this.template = Utils.templates.map;
      // when I am in the DOM, I can start adding all the Leaflet stuff
      this.listenTo(this, "inTheDOM", this.addMap);
    },

    render: function() {
      $(this.el).html(this.template({}));
      return this;
    },


    mymap: function() {

      // create a map in the "map" div, set the view to a given place and zoom
      var map = L.map('map').setView([51.505, -0.09], 13);

      // add an OpenStreetMap tile layer
      L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
          attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
      }).addTo(map);

      // add a marker in the given location, attach some popup content to it and open the popup
      L.marker([51.5, -0.09]).addTo(map)
          .bindPopup('A pretty CSS3 popup. <br> Easily customizable.')
          .openPopup();
    },


    //PRENDE IL VALORE DAL CAMPO RICERCA E FA LA QUERY AL DATABASE PER INSERIRE IL MARKER

    addMarkerToMap: function() {
        var Prodotti = Parse.Object.extend("Prodotti");
        //var self=this;
        var query = new Parse.Query(Prodotti);
        var prendiInput=$('[id="ricerca"]').val();
        query.equalTo("Titolo", prendiInput);
        query.find({
              success: function(Prodotti) {
                  var array= new Array();
                  var tmp,lat,longi;
                    for (var i = 0; i < Prodotti.length; i++) { 
                        array[i]=Prodotti[i];
                        tmp=array[i].get("Posizione");
                        lat=JSON.stringify(tmp.latitude);
                        longi=JSON.stringify(tmp.longitude);
                        
                        //self.addMap(true);

                      
                        var BlueIcon = L.icon({
                                  iconUrl: './img/Marker_Blue.png',
                                  iconSize: [40, 55],
                              });

                        var marker1=L.marker([lat, longi], {
                                  icon: BlueIcon
                                  }).addTo(map);
                        
                                  //marker1.bindPopup("I am a green leaf.");
                        
                      //(Prodotti[i].id)  
                    
                    }

                    
              },
              error: function(object, error) {
              alert("Error: " + error.code + " " + error.message);
              // The object was not retrieved successfully.
              // error is a Parse.Error with an error code and description.
              }
          });
          


              
    },


    addMap: function(param) {
     

      // get the current location of the user
      navigator.geolocation.getCurrentPosition(function(position) {
            var latitudine=position.coords.latitude;
            var longitudine=position.coords.longitude;
            var options = {
            center: new L.LatLng(latitudine, longitudine),
            zoom: 12
          };
      
          // create the map
          var map = L.map('map', options);
          // say thanks to Leaflet
          map.attributionControl.setPrefix("Leaflet");

          // create a marker and add it to the map
          //L.marker([42.3676443, 13.3496695]).addTo(map);

          // create an icon for showing the user its current location
          var positionIcon = L.icon({
            iconUrl: './img/seiqui.png',
            iconSize: [40, 55],
          });
          var layer = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                      attribution: 'Map data &copy; OpenStreetMap',
                      maxZoom: 20
          });
          map.addLayer(layer);
          var marker=L.marker([position.coords.latitude, position.coords.longitude], {
                    icon: positionIcon
                    }).addTo(map);
          marker.bindPopup("<b>Hello world!</b><br>I am a popup.").openPopup();
          
          if(param){
            
          
          }
          else {

          }
      }, function() {});
      
    }

  });

  return MapView;

});